package yzy.test.beans;

import yzy.test.mvc.Controller;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class BeanFactory {
    private static Map<Class<?> , Object> classToBean = new ConcurrentHashMap<>();

    public static Object getBean(Class<?> cls){
        return classToBean.get(cls);
    }

    public static void initBean(List<Class<?>> classes) throws Exception {
        List<Class<?>> classList = new ArrayList<>(classes);
        for(Class cls : classList){
            if(!cls.isAnnotationPresent(Bean.class) && !cls.isAnnotationPresent(Controller.class) ){
                return;
            }
            //依赖注入
            classToBean.put(cls, doCreateBean(cls));
        }

    }

    private static Object doCreateBean(Class cls) throws IllegalAccessException, InstantiationException {
        Object bean = cls.newInstance();
        System.out.println("Prepare to init and inject " + cls.getSimpleName());
        Field[] fields = cls.getDeclaredFields();
        for(Field field : fields){
            if(field.isAnnotationPresent(AutoWired.class)){
                Class<?> fieldType =  field.getType();
                Object obj = getBean(fieldType);

                if(obj == null){
                    obj = doCreateBean(fieldType);
                }
                field.setAccessible(true);
                field.set(bean, obj);
            }
        }
        return bean;
    }

}
